package com.dc.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dc.base.BaseApiService;
import com.dc.base.BaseResponse;
import com.dc.core.bean.DCBeanUtils;
import com.dc.constant.Constants;
import com.dc.core.utils.MD5Util;
import com.dc.member.feign.MemberFeignWeixinVerficode;
import com.dc.member.input.dto.UserInputDTO;
import com.dc.member.mapper.UserMapper;
import com.dc.member.mapper.entity.UserDO;
import com.dc.member.service.IMemberRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MemberRegisterServiceImpl extends BaseApiService<JSONObject> implements IMemberRegisterService {

    @Autowired
    private MemberFeignWeixinVerficode verficode;

    @Autowired
    private UserMapper userMapper;

    //@RequestBody 获取接口传递的数据  UserEntity json
    @Transactional
    @Override
    public BaseResponse<JSONObject> register(@RequestBody UserInputDTO userInputDTO, String registCode) {
        //1、参数验证
        String userName = userInputDTO.getUserName();
        if (StringUtils.isEmpty(userName)) {
            return setResultError("用户名称不能为空");
        }
        String mobile = userInputDTO.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            return setResultError("手机号不能为空");
        }
        String password = userInputDTO.getPassword();
        if (StringUtils.isEmpty(password)) {
            return setResultError("密码不能为空");
        }
        //2、验证注册码是否正确  会员调用微信接口，实现注册码验证
        BaseResponse<JSONObject> verificaWeixinCode = verficode.verificaWeixinCode(mobile, registCode);
        if (!verificaWeixinCode.getRtnCode().equals(Constants.HTTP_RES_CODE_200)) {
            return setResultError(verificaWeixinCode.getMsg());
        }
        //3、对用户密码加密
        String newpassword = MD5Util.MD5(password);
        userInputDTO.setPassword(newpassword);
        //4、调用数据库插入数据
        // inputDTO转换成DO实体类 直接封装成一个工具类
        //BeanUtils.copyProperties(userInputDTO, userDO);  // in  out 转换
        UserDO userDO = DCBeanUtils.dtoToDo(userInputDTO, UserDO.class);
        return userMapper.register(userDO) > 0 ? setResultSuccess("注册成功") : setResultError("注册失败");
    }
}
